import axios from 'axios';
import { ThunkAction } from 'redux-thunk';

import { BASE_URL } from '../../config';
import { RootState } from '../store';

export const FETCH_RECOMMEND_PRODUCTS_START = 'fetch_recommend_products_start'; // 开始调用
export const FETCH_RECOMMEND_PRODUCTS_SUCCESS = 'fetch_recommend_products_success'; // 调用成功
export const FETCH_RECOMMEND_PRODUCTS_FAIL = 'fetch_recommend_products_fail'; // 调用失败

interface FetchRecommendProductStartAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_START;
}

interface FetchRecommendProductSuccessAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_SUCCESS;
  payload: any;
}

interface FetchRecommendProductFailAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_FAIL;
  payload: any;
}

export type RecommendProductsAction =
  | FetchRecommendProductStartAction
  | FetchRecommendProductSuccessAction
  | FetchRecommendProductFailAction;

export const fetchRecommendProductStartActionCreator = (): FetchRecommendProductStartAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_START
  };
};

export const fetchRecommendProductSuccessActionCreator = (
  data
): FetchRecommendProductSuccessAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_SUCCESS,
    payload: data
  };
};
export const fetchRecommendProductFailActionCreator = (error): FetchRecommendProductFailAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_FAIL,
    payload: error
  };
};

export const giveMeDataActionCreator =
  (): ThunkAction<void, RootState, unknown, RecommendProductsAction> =>
  async (dispatch, getState) => {
    dispatch(fetchRecommendProductStartActionCreator());
    try {
      const {
        data: { data }
      } = await axios.get(`${BASE_URL}/productList`);
      dispatch(fetchRecommendProductSuccessActionCreator(data));
    } catch (error) {
      dispatch(fetchRecommendProductFailActionCreator(error.message));
    }
  };
